/**
* Copyright @ 2023 iAuto (Shanghai) Co., Ltd.
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are NOT permitted except as agreed by
* iAuto (Shanghai) Co., Ltd.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/



// 导入弹框
import React, { forwardRef, useCallback, useImperativeHandle, useMemo, useState } from 'react';
import { inportFileProps } from '@/types/soaManage';
import {
    UploadFile
} from 'antd/es/upload/interface';
import {
    Row,
    Col,
    Input,
    Upload,
    message,
    Button,
    Select,
    Divider,
    Form,
} from 'antd';
import CarModelTreeSelect from '@/components/CarModelTreeSelect';
import ModalWin from '@/components/common/ModalWin';
// import ShButton from '@/components/ShButton';
import BtnModal from './BtnModal';
import SocVersionInput from './SocVersionInput';
import styles from './index.less'
import { useRequest } from 'ahooks';
import { getSeriesModelList } from '@/services/soa/sceneOfficial';
import CarModel from './CarModel';

const labelStyle = {
    textAlign: 'right', paddingRight: 10,
}
const { Option } = Select;

export default forwardRef(
    (props: inportFileProps, ref: any) => {
        const {
            showModal,
            setShowModal,
            btnLoading,
            titleModal,
            submitModal,
            btnModalShow,
            btnsText = {},
            setBtnModalShow,
            // 车型车系数组
            carListCascader = []
        } = props
        const [selectedCarVal, setSelectedCarVal] = React.useState<any[]>([])
        // 设置服务版本
        const [importCarModeVersion, setImportCarModeVersion] = useState<any>({
            majorVersion: '',
            minorVersion: '',
        });
        const [form] = Form.useForm();
        // 服务文件
        const [socFileList, setSocFileList] = useState<UploadFile[]>([]);
        // 获取车系车型
        const seriesModelList = useRequest(getSeriesModelList);

        const submitForm = useMemo(
            () =>
                () => {
                    let { carSeries, carModels } = form.getFieldsValue();
                    if (!carSeries?.length) {
                        carSeries = selectedCarVal[0] || []
                    }
                    if (!carModels?.length) {
                        carModels = selectedCarVal[1] || []
                    }
                    if (!carSeries?.length) {
                        // 没有选择车系
                        message.warning('请选择车系!');
                        return
                    }
                    if (!carModels?.length) {
                        // 没有选择车型
                        message.warning('请选择车型!');
                        return
                    }
                    // 缓存数据
                    setSelectedCarVal([carSeries, carModels])
                    if (!(importCarModeVersion.majorVersion && importCarModeVersion.minorVersion)) {
                        // 没有设置版本
                        message.warning('请输入服务矩阵版本号!');
                        return
                    }
                    if (!socFileList || !socFileList.length) {
                        // 没有选择文件
                        message.warning('请选择文件!');
                        return
                    }
                    // 点击导入按钮关闭弹窗 -修复前端点击导入重复发请求问题
                    setShowModal(false);
                    const formattedVersion = `V${importCarModeVersion.majorVersion}.${importCarModeVersion.minorVersion}`
                    submitModal({
                        selectedCarVal: [carSeries[0], carModels.join(',')],
                        importCarModeVersion: formattedVersion,
                        socFileList
                    })
                }
            , [form, importCarModeVersion, socFileList, submitModal]
        )
        // 弹窗底部按钮
        const domFooter = useMemo(
            () => [<Button key="1"
                size="small"
                onClick={() => {
                    setShowModal(false);
                    resetFormData();
                }}>取消</Button>,
            <Button key="2"
                size="small"
                type='primary'
                onClick={submitForm}>导入</Button>
            ],
            [btnLoading, submitForm]
        )
        const resetFormData = useCallback(
            () => {
                setImportCarModeVersion({
                    majorVersion: '',
                    minorVersion: '',
                })
                setSelectedCarVal([])
                setSocFileList([])
                console.log("🚀 ~ file: InportFile.tsx ~ line 134 ~ resetFormData")
                form.resetFields()
            }, []
        )
        useImperativeHandle(ref, () => {
            return {
                resetFormData
            }
        })

        const handleCancel = () => {
            setShowModal(false);
            // resetFormData()
            form.resetFields()
        }

        // 设置版本号
        const domCarModeVersion = useMemo(
            () =>
                <Row style={{ marginTop: 20 }}>
                    <Col span={6} style={labelStyle}><span style={{ color: '#EC5353' }}>*</span> 服务矩阵版本号:</Col>
                    <Col span={18}>
                        <SocVersionInput setMajorVal={(val: string) => {
                            setImportCarModeVersion((prevData: any) => ({
                                ...prevData,
                                majorVersion: val,
                            }));
                        }} setMinorVal={(val: string) => {
                            setImportCarModeVersion((prevData: any) => ({
                                ...prevData,
                                minorVersion: val,
                            }));
                        }} />
                    </Col>
                </Row>,
            [importCarModeVersion]
        )
        // 服务文件
        const domUpload = useMemo(
            () =>
                <Row style={{ marginTop: 20 }}>
                    <Col span={6} style={labelStyle}><span style={{ color: '#EC5353' }}>*</span> 选择文件:</Col>
                    <Col span={18}>
                        <Upload
                            showUploadList={false}
                            onRemove={
                                (file) => {
                                    const index = socFileList.indexOf(file);
                                    const newFileList = socFileList.slice();
                                    newFileList.splice(index, 1);
                                    setSocFileList(newFileList);
                                }
                            }
                            beforeUpload={
                                (file) => {
                                    // setFileList([...fileList, file]);
                                    setSocFileList([file]);
                                    return false;
                                }
                            }
                            fileList={socFileList}
                            accept=".xls,.xlsx" maxCount={1}>
                            <Input
                                style={{ width: 320 }}
                                value={socFileList.length > 0 ? socFileList[socFileList.length - 1].name : ''}
                            />
                            {/* <Button type="primary" size='small' style={{ marginLeft: '14px' }} icon={<UploadOutlined />}>选择</Button> */}
                            <Button type="link" size='small'>选择</Button>
                        </Upload>
                    </Col>
                </Row>,
            [socFileList]
        )
        {/* 导入校验步骤２ */ }
        const domBtnModal = useMemo(
            () =>
                <BtnModal
                    btnModalShow={btnModalShow}
                    btnsText={btnsText}
                    submitModal={submitForm}
                    setBtnModalShow={
                        () => {
                            setBtnModalShow()
                            resetFormData()
                        }
                    }>
                </BtnModal>,
            [btnModalShow, btnsText, submitForm]
        )
        return (<>
                <ModalWin
                    wrapClassName={styles.importModal}
                    key={'showModal'}
                    title={titleModal}
                    visible={showModal}
                    destroyOnClose={true}
                    onCancel={handleCancel}
                    width={580}
                    footer={domFooter}
                >
                    <CarModel
                        form={form}
                        seriesModelList={seriesModelList}
                    />
                    {domCarModeVersion}
                    {domUpload}
                </ModalWin>
            {domBtnModal}
        </>)
    }
)